<template>
  <div class="course-score-container">
    <div class="header">
      <h2>课程得分管理</h2>
      <el-button type="primary" @click="handleAdd" v-if="hasPermission(['SYSTEM_ADMIN', 'TEACHER'])">
        添加课程得分
      </el-button>
    </div>

    <div class="filter-container">
      <el-input
        v-model="listQuery.courseCode"
        placeholder="课程代码"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter="handleFilter"
      />
      <el-input
        v-model="listQuery.courseName"
        placeholder="课程名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter="handleFilter"
      />
      <el-select v-model="listQuery.courseType" placeholder="课程类型" clearable style="width: 120px" class="filter-item">
        <el-option v-for="item in courseTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" @click="handleReset">
        重置
      </el-button>
    </div>

    <el-table :data="scoreList" border style="width: 100%" v-loading="loading">
      <el-table-column prop="studentId" label="学号" width="120" />
      <el-table-column prop="graduateName" label="学生姓名" width="120" />
      <el-table-column prop="courseCode" label="课程代码" width="120" />
      <el-table-column prop="courseName" label="课程名称" width="180" />
      <el-table-column prop="courseType" label="课程类型" width="100">
        <template #default="scope">
          {{ scope.row.courseType === 'REQUIRED' ? '必修' : '选修' }}
        </template>
      </el-table-column>
      <el-table-column prop="credit" label="学分" width="80" />
      <el-table-column prop="score" label="得分" width="100" />
      <el-table-column prop="comment" label="评价" />
      <el-table-column label="操作" width="150" v-if="hasPermission(['SYSTEM_ADMIN', 'TEACHER'])">
        <template #default="scope">
          <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(scope.row)" v-if="hasPermission(['SYSTEM_ADMIN'])">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="课程" prop="courseId">
          <el-select v-model="form.courseId" placeholder="请选择课程" style="width: 100%">
            <el-option
              v-for="course in courseList"
              :key="course.id"
              :label="course.courseName"
              :value="course.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="得分" prop="score">
          <el-input-number
            v-model="form.score"
            :min="0"
            :max="100"
            :precision="2"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="评价" prop="comment">
          <el-input
            v-model="form.comment"
            type="textarea"
            :rows="3"
            placeholder="请输入评价"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getStudentCourseScores, createCourseScore, updateCourseScore, deleteCourseScore } from '../../api/courseScore'
import { getCourseList } from '../../api/course'
import { useUserStore } from '../../store'
import { hasPermission } from '../../utils/permission'

const userStore = useUserStore()
const loading = ref(false)
const scoreList = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const courseList = ref([])

// 查询条件
const listQuery = ref({
  page: 1,
  limit: 20,
  courseCode: undefined,
  courseName: undefined,
  courseType: undefined
})

// 课程类型选项
const courseTypeOptions = [
  { label: '必修', value: 'REQUIRED' },
  { label: '选修', value: 'ELECTIVE' }
]

const form = ref({
  id: null,
  graduateId: null,
  courseId: null,
  score: null,
  comment: ''
})

const rules = {
  courseId: [{ required: true, message: '请选择课程', trigger: 'change' }],
  score: [{ required: true, message: '请输入成绩', trigger: 'blur' }]
}

// 获取课程得分列表
const fetchScoreList = async () => {
  loading.value = true
  try {
    const params = {
      courseCode: listQuery.value.courseCode,
      courseName: listQuery.value.courseName,
      courseType: listQuery.value.courseType
    }
    // 如果是毕业生，则只查询自己的成绩
    if (userStore.isGraduate) {
      params.graduateId = userStore.userInfo.id
    }

    console.log('发送请求获取课程得分列表，参数:', params)
    const { data } = await getStudentCourseScores(params)
    console.log('获取到的课程得分列表:', data)
    scoreList.value = data
  } catch (error) {
    console.error('获取课程得分列表失败:', error)
    ElMessage.error('获取课程得分列表失败')
  } finally {
    loading.value = false
  }
}

// 获取课程列表
const fetchCourseList = async () => {
  try {
    const { data } = await getCourseList()
    courseList.value = data
  } catch (error) {
    console.error('获取课程列表失败:', error)
    ElMessage.error('获取课程列表失败')
  }
}

// 搜索
const handleFilter = () => {
  fetchScoreList()
}

// 重置搜索条件
const handleReset = () => {
  listQuery.value = {
    page: 1,
    limit: 20,
    courseCode: undefined,
    courseName: undefined,
    courseType: undefined
  }
  fetchScoreList()
}

// 添加课程得分
const handleAdd = () => {
  dialogTitle.value = '添加课程得分'
  form.value = {
    id: null,
    graduateId: userStore.userInfo.id,
    courseId: null,
    score: null,
    comment: ''
  }
  dialogVisible.value = true
}

// 编辑课程得分
const handleEdit = (row) => {
  dialogTitle.value = '编辑课程得分'
  form.value = { ...row }
  dialogVisible.value = true
}

// 删除课程得分
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该课程得分记录吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteCourseScore(row.id)
      ElMessage.success('删除成功')
      fetchScoreList()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (form.value.id) {
          await updateCourseScore(form.value)
          ElMessage.success('更新成功')
        } else {
          await createCourseScore(form.value)
          ElMessage.success('添加成功')
        }
        dialogVisible.value = false
        fetchScoreList()
      } catch (error) {
        ElMessage.error(form.value.id ? '更新失败' : '添加失败')
      }
    }
  })
}

onMounted(() => {
  fetchScoreList()
  fetchCourseList()
})
</script>

<style scoped>
.course-score-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-container {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-item {
  margin-right: 10px;
}

.debug-info {
  margin: 20px 0;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 